package com.sita.redsun.connector.handler;

import com.sita.redsun.util.ByteBufUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.commons.lang3.ArrayUtils;
import java.util.List;

/**
 * Created by zhebinwang on 2017/3/28.
 */
public class DecoderHandler extends ByteToMessageDecoder {


    //该方法貌似对收到的数据进行拆包和拼包，
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
        if (!ctx.channel().isActive()) {
            return;
        }
        byte[] copiedBytes2 = new byte[buf.readableBytes()];

        //ByteBuf start = Unpooled.wrappedBuffer(Protocal.STARTING);
        byte[] STARTING = {(byte) 0x78, (byte) 0x78};
        byte[] ENDDING = {(byte) 0x0D, (byte) 0x0A};

        ByteBuf start = Unpooled.wrappedBuffer(STARTING);
        ByteBuf end = Unpooled.wrappedBuffer(ENDDING);

        int aIndex = ByteBufUtil.indexOf(buf, start);
        int bIndex = ByteBufUtil.indexOf(buf, end);
        //如果包头不在开始，并且包尾 在包头之后，那么说明包头前面的数据无用
        if (aIndex > 0 && aIndex < bIndex) {
            buf.skipBytes(aIndex);
        }

        //如果包头包尾同时存在，并且包头在包尾之前
        //逻辑是从包头开始，读取长度那么多的字节数，如果空间不够，就抛弃，否则就将读取的字节，插入到list<object>
        //中去
        byte[] copiedBytes1 = new byte[buf.readableBytes()];
        if (aIndex != -1 && bIndex != -1 && aIndex < bIndex) {
            byte[] copiedBytes = new byte[buf.readableBytes()];
            int readerIndex = buf.readerIndex();
            buf.getBytes(readerIndex, copiedBytes);

            int remaining = copiedBytes.length;
            if (remaining < 2){
                copiedBytes = null;
                return;
            }
            int pos = 0;
            // start
            byte[] startBytes = new byte[2];
            System.arraycopy(copiedBytes, pos, startBytes, 0, startBytes.length);
            pos += startBytes.length;

            remaining = copiedBytes.length - pos;
            if (remaining == 0){
                copiedBytes = null;
                return;
            }

            // length
            byte lengthByte = copiedBytes[pos];
            pos += 1;
            int length = lengthByte & 0xff;

            remaining = copiedBytes.length - pos;
            if (remaining < length){
                copiedBytes = null;
                return;
            }

            byte[] contentBytes = new byte[length];
            System.arraycopy(copiedBytes, pos, contentBytes, 0, contentBytes.length);
            pos += contentBytes.length;

            remaining = copiedBytes.length - pos;
            if (remaining < 2){
                copiedBytes = null;
                return;
            }
            // end
            byte[] endBytes = new byte[2];
            System.arraycopy(copiedBytes, pos, endBytes, 0, endBytes.length);
            pos += endBytes.length;

            byte[] msgData = ArrayUtils.addAll(startBytes, lengthByte);
            msgData = ArrayUtils.addAll(msgData, contentBytes);
            msgData = ArrayUtils.addAll(msgData, endBytes);

            // 数据完整
            copiedBytes = null;
            buf.skipBytes(msgData.length);

            out.add(msgData);
            try {
               /* PacketUp packet = PacketUp.parse(msgData);
                if (packet != null) {
                    packet.setOrigHex(msgData);
                    out.add(packet);
                }*/
              /*  if (logger.isInfoEnabled()) {
                    logger.info("{} RECEIVE_DATA: cmdId=[{}], data=[{}]",
                            KksModServer.serverName,
                            packet.getCmdId(),
                            BaseEncoding.base16().encode(msgData));
                }*/
            } catch (Exception e) {
               /* if (logger.isInfoEnabled()) {
                    logger.info("{} 收到未知上行数据, data=[{}]",
                            KksModServer.serverName,
                            BaseEncoding.base16().encode(msgData));
                }*/
               e.printStackTrace();
            }
        }
    }
}
